package mobi.zeedev.flyingsaucer.common.DataModule.tree;

import java.util.Iterator;
import java.util.List;

/**
 * User: James
 * Date: 12/28/10
 * Time: 1:14 AM
 */
public class DatabaseTree extends Tree<Void> implements Iterable<DatabaseNode>, IDatabaseTree {

    @Override
    public Iterator<DatabaseNode> iterator() {

        final List l = this.toList();


        return new Iterator<DatabaseNode>() {

            int i = 0;
            int max = l.size();

            @Override
            public boolean hasNext() {
                if (i >= max) {
                    return false;
                } else {
                    return true;
                }
            }

            @Override
            public DatabaseNode next() {

                DatabaseNode node = (DatabaseNode) l.get(i);
                i++;
                return node;

            }

            @Override
            public void remove() {
//                i++;
            }
        };
    }


    @Override
    public DatabaseNode addAttributeToKey(Object primaryKeyValue, String columnName, String attributeValue) {
        return this.findPrimaryKeyNode(primaryKeyValue).addAttribute(columnName, attributeValue);
    }


    @Override
    public DatabaseNode addTable(String tableName) {

        this.setRootElement(DatabaseNode.TableNode(tableName));
        return this.getRootElement();

    }

    @Override
    public DatabaseNode addPrimaryKey(Object columnName, Object keyValue) {
        DatabaseNode ret = DatabaseNode.PrimaryKeyNode(columnName, keyValue);
        this.getRootElement().addChild(ret);
        return ret;
    }

    @Override
    public DatabaseNode getRootElement() {
        return (DatabaseNode) super.getRootElement();
    }


    private DatabaseNode findPrimaryKeyNode(Object primaryKeyValue) {

        DatabaseNode ret = null;

        for (DatabaseNode curNode : this) {
            if (curNode.getType() == DatabaseType.PRIMARY_KEY && curNode.getValue().equals(primaryKeyValue)) {
                ret = curNode;
                break;
            }
        }
        return ret;
    }




}
